set seed 21112023

local bsamplesize = 100

*******SAVING THE INITIAL SET OF OBSERVATIONS FOR B-SAMPLING**************
use "$working/Demand_TFPQIV_CS_klme_nic4_sampleFS", clear
merge 1:1 co_code1 year using "$working/CS_nic4_klme_sampleSS" // OPF, NIC2 and NIC4 are all the same


generate mid_s = 1 if _merge==3 // D and SS
replace mid_s = 2 if _merge==1 // D only
replace mid_s = 3 if _merge==2 // SS only

drop _merge

merge  1:1 co_code1 year using "$working/CS_klme_sampleFS"

generate samples = 1 if _merge==3 & mid_s ==1 // D, FS, SS
replace samples = 2 if _merge==3 & mid_s==2 // D and FS
replace samples = 3 if _merge==3 & mid_s==3 // SS and FS

replace samples = 4 if _merge==1 & mid_s==1 // D and SS only
replace samples  = 5 if _merge==1 & mid_s==2 // D only
replace samples  = 6 if _merge==1 & mid_s==3 // SS only

replace samples = 7 if _merge==2 // FS only

tabulate samples

drop _merge mid_s

**Only need to put demand at product-level

merge 1:m co_code1 year using "$working/Demand_TFPQIV_CS_klme_nic4_sampleFS_prod"
drop _merge

preserve

	collapse (mean) samples, by(co_code1 year)

	sum

restore

tabulate samples

save "$working/sample_CS_klme", replace

forvalues bs = 1(1)`bsamplesize' {
	clear
	***Grab bootstrap samples
	use "$working/sample_CS_klme"
	egen firm_year = group(co_code1 year)
	bsample,  strata(sample) cluster(firm_year) idcluster(firm_year_bs)
	save "$BS_fold_old/record/CS/klme/lvl/bssample_`bs'", replace
}

